#!/bin/bash
if [[ $# != 2 ]]
then
    echo "usage: cpc <command> <destination_root>"
    exit -1
fi
# support full path command
if [[ $1 =~ "/" ]]; then # path
    commands=$1
else
    commands=`which $1`
fi

# use find to support simple regular expression
commands=`find $commands`

sys_root=$2
if [[ "${sys_root:0-1}" == "/" ]]; then
    sys_root=${sys_root%?}
fi

if [ -z "${sys_root}" ] || [ ! -d ${sys_root} ]
then
    echo "Error: invalid destination root path."
    exit -1
fi

function check_usr_link {
    local path=$1
    local dst_root=$2
    root_removed=${path#/}
    top_dir=${root_removed%%/*}
    case $top_dir in
        bin)
        ;&
        lib)
        ;&
        lib64)
        ;&
        libx32)
        cp -d /${top_dir} ${dst_root}
        echo "/usr$path"
        ;;
    esac
}

function rcopywd {
#    echo "Source:$1"
    local src=$1
    local dst_root=$2
    local new_src=`check_usr_link $src $dst_root`
    if [[ "$new_src " != " " ]]; then
        src=$new_src
    fi
    if [[ "$src" != /* ]]; then
        # Source must be absolute path
        return -1
    fi
    local src_base=`basename $src`
    local src_dir=`dirname $src`
    local link=
    local depends=
    # if exist
    if [ ! -e ${dst_root}${src} ]; then
        # src has not been copied
        cp -d --parents $src $dst_root &> /dev/null
    fi
    # if soft link, copy soft link self, dereference
    if [ -h $src ]; then
        link_ctn=`readlink $src`
        if [[ "$link_ctn" = /* ]]; then
            link=$link_ctn
        else
            link=${src_dir}/${link_ctn}
        fi
        rcopywd $link $dst_root
    # copy with depend
    else
        depends=`ldd $src | awk '{print $(NF-1)}'` 
        for depend in $depends
        do
            rcopywd $depend $dst_root
        done
       
    fi
}

for cmd in $commands
do
    if [ -d $cmd ]
    then
        continue # filter directory
    fi
    rcopywd $cmd $sys_root
done

function copy_depend() {
    echo "depend: $1"
    # copy dependency
    local depend=`ldd $1 | awk '{print $(NF-1)}'`
    for line in $depend
    do
	echo $line
        if [ -e ${line} ]; then
            if [ -e ${sys_root}${line} ]; then
                echo "Dependency ${line} already copied."
	    elif [ -h ${line} ]; then
		cp -d --parents ${line} ${sys_root} &> /dev/null
		echo "Follow softlink ${line}..."
		link_base=`dirname ${line}`
		echo ${link_base}
		link=`readlink ${line}`
		echo $link
		if [[ "${link}" = /* ]]; then
            
		    copy_depend ${link}
		else
		    copy_depend ${link_base}/${link} 
		fi	
            else
                cp --parents ${line} ${sys_root} &> /dev/null
                echo "Copy dependency ${line} to ${sys_root}${line}."
                copy_depend ${line}
            fi
        fi    
    done
}
